/*
 * Copyright (C) 2007 ETH Zurich
 *
 * This file is part of Fosstrak (www.fosstrak.org).
 *
 * Fosstrak is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software Foundation.
 *
 * Fosstrak is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Fosstrak; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */
package com.qf.cx.simplenms.subscriber.type;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * abstract class that can be used in order to send a given message using a socket.
 * @author swieland
 */
public abstract class AbstractSocketSubscriberOutputChannel extends AbstractSubscriberOutputChannel {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * This method writes data to a socket with host name and port number of this subscriber.
	 *
	 * @param data to write to the socket
	 */
	protected void writeToSocket(String data) {
		Socket socket;
		try {

			// open socket and stream
			socket = getSocket();
			BufferedOutputStream dataOutputStream = new BufferedOutputStream(socket.getOutputStream());

			// write reports
			dataOutputStream.write(data.getBytes("UTF-8"));
			dataOutputStream.flush();

			// close socket and stream
			dataOutputStream.close();
			socket.close();

		} catch (UnknownHostException e) {
			logger.error("unknown host: ", e);
		} catch (IOException e) {
			logger.error("io exception: ", e);
		}
	}

	/**
	 * @return get a socket for the connection.
	 * @throws IOException some other io issue.
	 * @throws UnknownHostException unknown host.
	 */
	protected Socket getSocket() throws UnknownHostException, IOException {
		return new Socket(getHost(), getPort());
	}

	/**
	 * @return the host to be use in order to establish the connection.
	 */
	public abstract String getHost();

	/**
	 * @return the port to use in order to establish the connection.
	 */
	public abstract int getPort();

}
